<template>
  <div class="pet-management">
    <div class="page-header">
      <h2>宠物管理</h2>
      <el-button type="primary" @click="handleAdd">新增宠物</el-button>
    </div>

    <!-- 搜索栏 -->
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="宠物名称">
          <el-input v-model="searchForm.name" placeholder="请输入宠物名称" clearable />
        </el-form-item>
        <el-form-item label="类型">
          <el-select v-model="searchForm.category" placeholder="请选择类型" clearable>
            <el-option label="猫" value="猫" />
            <el-option label="狗" value="狗" />
            <el-option label="其他" value="其他" />
          </el-select>
        </el-form-item>
        <el-form-item label="领养状态">
          <el-select v-model="searchForm.adoptionStatus" placeholder="请选择领养状态" clearable>
            <el-option label="待领养" value="AVAILABLE" />
            <el-option label="已领养" value="ADOPTED" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 宠物列表 -->
    <el-card class="list-card">
      <el-table
        v-loading="loading"
        :data="petList"
        border
        style="width: 100%">
        <el-table-column prop="name" label="宠物名称" min-width="120" />
        <el-table-column prop="category" label="类型" width="100" />
        <el-table-column prop="breed" label="品种" min-width="120" />
        <el-table-column prop="age" label="年龄" width="80">
          <template slot-scope="scope">
            {{ scope.row.age }}岁
          </template>
        </el-table-column>
        <el-table-column prop="gender" label="性别" width="80" />
        <el-table-column prop="healthStatus" label="健康状况" min-width="120" />
        <el-table-column prop="adoptionStatus" label="领养状态" width="100">
          <template slot-scope="scope">
            <el-tag :type="scope.row.adoptionStatus === 'AVAILABLE' ? 'success' : 'info'">
              {{ scope.row.adoptionStatus === 'AVAILABLE' ? '待领养' : '已领养' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="imageUrl"
          label="图片"
          width="120"
          align="center">
          <template slot-scope="scope">
            <el-image
              v-if="scope.row.imageUrl"
              :src="getImageUrl(scope.row.imageUrl)"
              :preview-src-list="[getImageUrl(scope.row.imageUrl)]"
              style="width: 80px; height: 80px">
            </el-image>
            <span v-else>无图片</span>
          </template>
        </el-table-column>
        <el-table-column prop="createdTime" label="创建时间" width="180">
          <template slot-scope="scope">
            {{ formatTime(scope.row.createdTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              @click="handleEdit(scope.row)">编辑</el-button>
            <el-button
              size="mini"
              type="danger"
              @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="page.pageNum"
          :page-sizes="[10, 20, 30, 50]"
          :page-size="page.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="page.total"
        />
      </div>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="600px">
      <el-form
        :model="petForm"
        :rules="rules"
        ref="petForm"
        label-width="100px"
      >
        <el-form-item label="宠物名称" prop="name">
          <el-input v-model="petForm.name" placeholder="请输入宠物名称" />
        </el-form-item>
        <el-form-item label="类型" prop="category">
          <el-select v-model="petForm.category" placeholder="请选择类型">
            <el-option label="猫" value="猫" />
            <el-option label="狗" value="狗" />
            <el-option label="其他" value="其他" />
          </el-select>
        </el-form-item>
        <el-form-item label="品种" prop="breed">
          <el-input v-model="petForm.breed" placeholder="请输入品种" />
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input-number v-model="petForm.age" :min="0" :max="30" />
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-radio-group v-model="petForm.gender">
            <el-radio label="公">公</el-radio>
            <el-radio label="母">母</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="健康状况" prop="healthStatus">
          <el-input v-model="petForm.healthStatus" placeholder="请输入健康状况" />
        </el-form-item>
        <el-form-item label="领养状态" prop="adoptionStatus">
          <el-select v-model="petForm.adoptionStatus" placeholder="请选择领养状态">
            <el-option label="待领养" value="AVAILABLE" />
            <el-option label="已领养" value="ADOPTED" />
          </el-select>
        </el-form-item>
        <el-form-item label="图片">
          <div class="custom-upload">
            <div 
              class="upload-box" 
              @click="triggerFileInput"
              :style="petForm.imageUrl || localPreviewUrl ? 'border: none' : ''"
            >
              <template v-if="petForm.imageUrl">
                <img :src="getImageUrl(petForm.imageUrl)" class="preview-image" />
              </template>
              <template v-else-if="localPreviewUrl">
                <img :src="localPreviewUrl" class="preview-image" />
                <div class="uploading-overlay">
                  <i class="el-icon-loading"></i>
                  <span>上传中...</span>
                </div>
              </template>
              <template v-else>
                <i class="el-icon-plus"></i>
                <div>点击上传图片</div>
              </template>
            </div>
            <input 
              type="file" 
              ref="fileInput" 
              style="display: none" 
              accept="image/jpeg,image/png" 
              @change="onFileChange"
            />
            <div v-if="petForm.imageUrl || localPreviewUrl" class="image-actions">
              <el-button type="text" size="small" @click.stop="removeImage">删除图片</el-button>
            </div>
          </div>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            type="textarea"
            v-model="petForm.description"
            :rows="3"
            placeholder="请输入描述信息"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleSubmit">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getPetList, createPet, updatePet, deletePet } from '@/api/admin'
import { getToken } from '@/utils/auth'

export default {
  name: 'PetManagement',
  
  data() {
    return {
      loading: false,
      petList: [],
      searchForm: {
        name: '',
        category: '',
        adoptionStatus: ''
      },
      page: {
        pageNum: 1,
        pageSize: 10,
        total: 0
      },
      dialogVisible: false,
      dialogType: 'add',
      petForm: {
        name: '',
        category: '',
        breed: '',
        age: 0,
        gender: '公',
        healthStatus: '',
        adoptionStatus: 'AVAILABLE',
        imageUrl: '',
        description: ''
      },
      rules: {
        name: [
          { required: true, message: '请输入宠物名称', trigger: 'blur' },
          { min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur' }
        ],
        category: [
          { required: true, message: '请选择类型', trigger: 'change' }
        ],
        breed: [
          { required: true, message: '请输入品种', trigger: 'blur' }
        ],
        age: [
          { required: true, message: '请输入年龄', trigger: 'blur' }
        ],
        gender: [
          { required: true, message: '请选择性别', trigger: 'change' }
        ],
        healthStatus: [
          { required: true, message: '请输入健康状况', trigger: 'blur' }
        ],
        adoptionStatus: [
          { required: true, message: '请选择领养状态', trigger: 'change' }
        ]
      },
      localPreviewUrl: null
    }
  },

  computed: {
    dialogTitle() {
      return this.dialogType === 'add' ? '新增宠物' : '编辑宠物'
    }
  },

  created() {
    this.fetchData()
  },

  methods: {
    formatTime(time) {
      if (!time) return ''
      const date = new Date(time)
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      const hours = String(date.getHours()).padStart(2, '0')
      const minutes = String(date.getMinutes()).padStart(2, '0')
      return `${year}-${month}-${day} ${hours}:${minutes}`
    },

    async fetchData() {
      this.loading = true
      try {
        const params = {
          pageNum: this.page.pageNum,
          pageSize: this.page.pageSize,
          ...this.searchForm
        }
        const response = await getPetList(params)
        if (response.code === 200 && response.data) {
          // 处理获取到的数据，确保图片路径完整
          this.petList = response.data.list.map(pet => {
            if (pet.imageUrl) {
              console.log('原始图片路径:', pet.imageUrl);
              // 不直接修改原数据，返回新对象
              return {
                ...pet,
                // 不在这里转换URL，只在显示时转换
                // 因为如果重复转换会导致URL变得很长
              };
            }
            return pet;
          });
          this.page.total = response.data.total
        }
      } catch (error) {
        console.error('获取宠物列表失败:', error)
        this.$message.error('获取宠物列表失败')
      } finally {
        this.loading = false
      }
    },

    handleSearch() {
      this.page.pageNum = 1
      this.fetchData()
    },

    resetSearch() {
      this.searchForm = {
        name: '',
        category: '',
        adoptionStatus: ''
      }
      this.handleSearch()
    },

    handleSizeChange(val) {
      this.page.pageSize = val
      this.fetchData()
    },

    handleCurrentChange(val) {
      this.page.pageNum = val
      this.fetchData()
    },

    handleAdd() {
      this.dialogType = 'add'
      this.petForm = {
        name: '',
        category: '',
        breed: '',
        age: 0,
        gender: '公',
        healthStatus: '',
        adoptionStatus: 'AVAILABLE',
        imageUrl: '',
        description: ''
      }
      this.dialogVisible = true
    },

    handleEdit(row) {
      this.dialogType = 'edit'
      // 复制一份数据，避免直接修改原始数据
      this.petForm = { ...row }
      
      // 打印图片路径，帮助调试
      console.log('编辑宠物，原始图片路径:', this.petForm.imageUrl);
      
      this.dialogVisible = true
    },

    async handleDelete(row) {
      try {
        await this.$confirm('确认删除该宠物信息吗？', '提示', {
          type: 'warning'
        })
        const response = await deletePet(row.id)
        if (response.code === 200) {
          this.$message.success('删除成功')
          this.fetchData()
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除失败:', error)
          this.$message.error('删除失败')
        }
      }
    },

    async handleSubmit() {
      this.$refs.petForm.validate(async valid => {
        if (!valid) return
        try {
          const submitData = { ...this.petForm }
          let response
          if (this.dialogType === 'add') {
            response = await createPet(submitData)
          } else {
            response = await updatePet(submitData.id, submitData)
          }
          if (response.code === 200) {
            this.$message.success(this.dialogType === 'add' ? '新增成功' : '编辑成功')
            this.dialogVisible = false
            this.fetchData()
          }
        } catch (error) {
          console.error(error)
          this.$message.error(this.dialogType === 'add' ? '新增失败' : '编辑失败')
        }
      })
    },

    triggerFileInput() {
      this.$refs.fileInput.click();
    },

    onFileChange(event) {
      const file = event.target.files[0];
      if (!file) return;
      
      // 校验文件类型和大小
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
      const isLt2M = file.size / 1024 / 1024 < 2;
      
      if (!isJPG) {
        this.$message.error('上传图片只能是 JPG 或 PNG 格式!');
        return;
      }
      
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!');
        return;
      }
      
      // 上传之前先显示本地预览图
      const reader = new FileReader();
      reader.onload = (e) => {
        // 先设置一个临时的本地预览URL
        this.localPreviewUrl = e.target.result;
      };
      reader.readAsDataURL(file);
      
      // 创建FormData进行实际上传
      const formData = new FormData();
      formData.append('file', file);
      formData.append('directory', 'pets');
      
      // 显示上传中状态
      const loading = this.$loading({
        lock: true,
        text: '图片上传中...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      
      // 导入uploadFile函数并执行上传
      import('@/api/admin').then(module => {
        const { uploadFile } = module;
        
        uploadFile(formData, {
          headers: {
            Authorization: 'Bearer ' + getToken()
          }
        }).then(response => {
          loading.close();
          
          if (response.code === 200) {
            // 设置从服务器返回的URL
            this.petForm.imageUrl = response.data;
            console.log('上传成功，服务器返回的图片路径:', response.data);
            console.log('完整的访问URL:', this.getImageUrl(response.data));
            this.$message.success('图片上传成功');
          } else {
            console.error('上传失败，服务器返回:', response);
            this.$message.error(response.message || '上传失败');
          }
        }).catch(error => {
          loading.close();
          console.error('上传请求错误:', error);
          this.$message.error('上传失败: ' + (error.message || '未知错误'));
        });
      });
    },

    removeImage() {
      this.petForm.imageUrl = '';
      this.localPreviewUrl = null;
      // 重置文件输入框
      if (this.$refs.fileInput) {
        this.$refs.fileInput.value = '';
      }
      this.$message.success('图片已删除');
    },

    // 新的图片URL获取方法
    getImageUrl(path) {
      if (!path) {
        console.log('图片路径为空');
        return '';
      }
      
      console.log('正在处理图片URL:', path);
      
      // 服务器地址
      const serverUrl = 'http://localhost:8080'; // 后端API服务器地址
      
      // 如果路径已经是完整URL，直接返回
      if (path.startsWith('http://') || path.startsWith('https://')) {
        console.log('图片路径是完整URL，直接返回:', path);
        return path;
      }
      
      // 确保路径以 / 开头
      if (!path.startsWith('/')) {
        path = '/' + path;
        console.log('添加前导斜杠后的路径:', path);
      }
      
      // 构建完整URL
      const fullUrl = serverUrl + path;
      console.log('构建的完整图片URL:', fullUrl);
      
      return fullUrl;
    },

    previewImage() {
      // 实现预览图片的逻辑
      console.log('预览图片:', this.petForm.imageUrl);
      if (!this.petForm.imageUrl) return;
      
      // 创建一个临时的大图预览
      const url = this.getImageUrl(this.petForm.imageUrl);
      const previewList = [url];
      
      // 使用Element UI的图片预览功能
      this.$image({
        urls: previewList,
        closeOnClickModal: true
      });
    }
  }
}
</script>

<style lang="scss" scoped>
.pet-management {
  padding: 20px;

  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    
    h2 {
      margin: 0;
    }
  }

  .search-card {
    margin-bottom: 20px;
  }

  .list-card {
    .pagination-container {
      margin-top: 20px;
      text-align: right;
    }
  }

  .avatar-uploader {
    :deep(.el-upload) {
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      
      &:hover {
        border-color: #409EFF;
      }
    }
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 120px;
    height: 120px;
    line-height: 120px;
    text-align: center;
  }

  .avatar {
    width: 120px;
    height: 120px;
    display: block;
    object-fit: cover;
  }

  .avatar-tip {
    margin-top: 10px;
    text-align: center;
  }

  .custom-upload {
    display: flex;
    flex-direction: column;
    align-items: flex-start;
    margin-bottom: 10px;

    .upload-box {
      width: 120px;
      height: 120px;
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      position: relative;
      overflow: hidden;

      &:hover {
        border-color: #409EFF;
      }

      i {
        font-size: 28px;
        color: #8c939d;
        margin-bottom: 8px;
      }

      div {
        color: #8c939d;
        font-size: 14px;
        text-align: center;
      }
    }

    input[type="file"] {
      display: none;
    }

    .image-actions {
      margin-top: 10px;
      align-self: center;
    }
  }

  .preview-image {
    width: 120px;
    height: 120px;
    object-fit: cover;
    display: block;
  }

  .uploading-overlay {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.5);
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;

    i {
      font-size: 24px;
      color: #fff;
      margin-bottom: 10px;
    }

    span {
      font-size: 14px;
      color: #fff;
    }
  }
}
</style> 